package demo4;

/**
 * Created with IntelliJ IDEA.
 * Description:对称二叉树
 * User: liangyuanzhang
 * Date: 2025-4-22
 * Time: 21:33
 */
class Test {
    public boolean isSymmetric(TreeNode root) {
        //首先判断树是否为空 这里认为空树也是对称的
        if(root == null) return true;
        return isSymmetricChild(root.left,root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        //两种情况，左子树或者右子树有一个为空，则不对称
        if(leftTree != null && rightTree == null || leftTree == null && rightTree != null)
            return false;
        //到这里有两种情况 1.两个边的子树都为空
        if(leftTree == null && rightTree == null) return true;
        //2.不为空之后就是开始比较值是否相同
        if(leftTree.val != rightTree.val) return false;
        //然后就是一直递归
        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }
}